# -*- coding: iso-8859-1 -*-
#
#    This is part of Malvinas Argentinas Messenger
#
#    Malvinas Argentinas Messenger is free software; you can redistribute
#    it and/or modify it under the terms of the GNU General Public License
#    as published by the Free Software Foundation; either version 2 of the
#    License, or (at your option) any later version.
#
#    Malvinas Argentinas Messenger is distributed in the hope that it will be
#    useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with Malvinas Argentinas Messenger; if not, write to the Free
#    Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
#    MA  02110-1301  USA

import datetime, time
import os
from ui import frontEnd, backEnd
from protocol import msnlib, msncb, msnft
from capa2b import callbacks
from capa2b import connectionManager
import gettext
_ = gettext.gettext

class OfflineMSG:
	def __init__(self, email = '', text = '', date = ''):
		self.email = email
		self.text = text
		self.date = date

class System:
	# Init method
	def __init__(self):
		# Initialize basic msnlib classes
		self.m = msnlib.msnd()
		self.m.cb = msncb.cb()

		# Build config
		self.config = self.getConfig('config')
		self.lastUserInteraction = datetime.datetime.now()
		self.m.encoding = self.config['encoding']
		
		# Log Startup event to file
		if self.config.has_key('events_log_path'):
			self.dumptoFile(str(self.config['events_log_path']), '\nMALVINAS' + _('STARTED') + '> ' + \
			time.strftime('%d/%m/%Y - %H:%M:%S', time.localtime()) , 1)
		
		# Build aliases List
		self.aliasesList = self.getAliases('.aliases')

		# Build favourite contacts list
		self.favList = self.getFav('.fav')

		# Build local offline msgs
		self.flnMsgsList = self.getFlnMsgs('.offline')

		# Set debugging
		if int(self.config['debug']) == 0:
			msnlib.debug = self.null
			msncb.debug = self.null

		# Build frontEnd
		self.ui = frontEnd.FrontEnd(self)

		# Build callbacks
		callbacks.buildCallbacks(self)

		# Build stdinManager
		self.stdinManager = backEnd.stdinManager(self)

		# Build contact list manager
		self.contactListManager = ''

		# Build display picture manager
		self.dpManager = ''

		# Build file transfer manager
		self.ftManager = msnft.ftManager()

		# Build connection manager, and do the infinite loop
		self.connectionManager = connectionManager.ConnectionManager(self)
		self.connectionManager.infiniteLoop()

# ------------------------------------------
# FlnMsg's methods

	def checkToSendOffline(self, user = ''):
		if self.ui.status not in ('FLN', 'HDN'):
			for m in self.flnMsgsList:
				if user:
					if user == m.email and self.contactListManager.userOnline(user):
						self.ui.printMsg('\n' + 'Offline MSG should be send here', self.ui.COLORS.RED_R)
						##if m.date == '':
						##	m.date = 1
						#r = self.m.sendmsg(m.email, m.text, '', 'A', "MIME-Version: 1.0\r\n" + "Content-Type: text/plain; charset=UTF-8\r\n\r\n", '')
						#if r == 2:
						self.deleteFlnMsg(user)
				else:					
					if self.contactListManager.userOnline(m.email):
						self.ui.printMsg('\n' + 'Offline MSG should be send here', self.ui.COLORS.RED_R)
						self.deleteFlnMsg(m.email)

	def deleteFlnMsg(self, email):
		sent = 0
		entireMsg = ''
		indices = []
		for i in self.flnMsgsList:
			if email == i.email:
				entireMsg += i.text + '\n'
				indices.append(i)
				sent += 1
		for i in indices:
			self.flnMsgsList.remove(i)
		if sent:
			self.dumpFlnMsgslist('.offline')
			self.ui.printMsg('\n%d %s:\n%s' % (sent, '%s' % _('Offline messages sent to') + ' ' + email, entireMsg), self.ui.COLORS.GREEN_R)
			self.ui.refreshScr()

	def addFlnMsg(self, email, text, date = ''):
		self.flnMsgsList.append(OfflineMSG(email, text, date))

	def getFlnMsgs(self, file):
		try:
			fd = open(file)
		except:			
			return []
		lines = fd.readlines()
		flnMsgsList = []
		for i in lines:
			i = i.strip()
			if not (i.find('\t') < 0 or i[0] == '#'):
				f = i.split('\t', 1)
				FlnMsg = OfflineMSG(f[0], f[1], '')
				flnMsgsList.append(FlnMsg)
		fd.close()
		return flnMsgsList

	def dumpFlnMsgslist(self, file):
		try:
			# Dump the msg to file
			fd = open(file, 'w')
			for i in self.flnMsgsList:
				fd.write(i.email + '\t' + i.text + '\n')
			fd.close()
		except IOError:
			self.ui.printMsg('\n' + _('Error dumping Offline Messages list to file.') + ' ' + _('Not write privilegies.'), self.ui.COLORS.RED_R)
			self.ui.padArray.refresh(_('EVENTS'))
			self.ui.padInput.refresh()
		except:
			self.ui.printMsg('\n' + _('Error dumping Offline Messages list to file.'), self.ui.COLORS.RED_R)
			self.ui.padArray.refresh(_('EVENTS'))
			self.ui.padInput.refresh()

# ------------------------------------------
	# Get aliases list from file
	def getAliases(self, file):
		try:
			fd = open(file)
		except:			
			return {}
		lines = fd.readlines()
		aliasesList = {}
		for i in lines:
			i = i.strip()
			if not (i.find('=') < 0 or i[0] == '#'):
				pal_email, nick = i.split(' = ', 1)
				aliasesList[pal_email] = nick
		fd.close()
		return aliasesList

	# Dump aliases list to file
	def dumpAliaseslist(self, file):
		try:
			fd = open(file, 'w')
			for i in self.aliasesList:
				fd.write(str(i) + ' = ' + self.aliasesList[i] + '\n')
			fd.close()
		except IOError:
			self.ui.printMsg('\n' + _('Error dumping aliases list to file.') + ' ' + _('Not write privilegies.'), self.ui.COLORS.RED_R)
			self.ui.padArray.refresh(_('EVENTS'))
			self.ui.padInput.refresh()
		except:
			self.ui.printMsg('\n' + _('Error dumping log to file.'), self.ui.COLORS.RED_R)
			self.ui.padArray.refresh(_('EVENTS'))
			self.ui.padInput.refresh()

	# From Alberto Bertogli's msnlib
	def getConfig(self, file):
		try:
			fd = open(file)
		except:
			return {}
		lines = fd.readlines()
		config = {}
		for i in lines:
			i = i.strip()
			if i.find('=') < 0:
				continue
			if i[0] == '#':
				continue
			var, value = i.split('=', 1)
			var = var.strip()
			value = value.strip()
			config[var] = value
		fd.close()
		return config

	# Dump msg to file
	def dumptoFile(self, file_name, text, newLine = 1):
		try:
			# Check permissions of directory
			if not os.access(self.config['conversations_log_path'], os.F_OK):
				os.system("mkdir -p %s" % self.config['conversations_log_path'])
			fd = open(file_name, 'a')
			if newLine:
				fd.write(text + '\n')
			else:
				fd.write(text)
			fd.close()
		except OSError:
			self.ui.printMsg('\n%s.' % _('Error making directories for logging'), self.ui.COLORS.ERROR1)
			self.ui.padArray.refresh(_('EVENTS'))
			self.ui.padInput.refresh()
		except IOError:
			self.ui.printMsg('\n%s %s' % (_('Error dumping log to file.'), _('Not write privilegies.')), self.ui.COLORS.ERROR1)
			self.ui.padArray.refresh(_('EVENTS'))
			self.ui.padInput.refresh()
		except:
			self.ui.printMsg('\n%s' % _('Error dumping log to file.'), self.ui.COLORS.ERROR1)
			self.ui.padArray.refresh(_('EVENTS'))
			self.ui.padInput.refresh()

	# Just a time test function for development 
	def timetest(self, expr):
		a = time.time()
		expr
		b = time.time()
		c = b - a
		ui.printMsg('\n%f' % c)
		ui.padArray.refresh(_('EVENTS'))

	# Get favourite contacts list from file
	def getFav(self, file):
		try:
			fd = open(file)
		except:			
			return {}
		lines = fd.readlines()
		favList = {}
		for i in lines:
			i = i.strip()
			if not (i.find('=') < 0 or i[0] == '#'):
				pal_email, soundPath = i.split(' = ', 1)
				favList[pal_email] = soundPath
		fd.close()
		return favList

	# Set debugging
	def null(self, s):
		"Null function, useful to void debug ones"
		pass
